﻿using System.Diagnostics;

namespace RFIDStation.DeviceDriver.IModules.Impls;

public class DaemonModule : IModule
{
    private readonly ILogger _logger;
    private readonly ViewModel _viewModel;

    public DaemonModule( ILoggerFactory loggerFactory, ViewModel viewModel )
    {
        _logger = loggerFactory.CreateLogger( "守护进程" );
        _viewModel = viewModel;
    }

    public async Task StartAsync( CancellationToken cancellationToken )
    {
        if ( _viewModel.AppConfig.Daemon.FilePath.IsNullOrWhiteSpace( ) ) return;

        var fi = new FileInfo( _viewModel.AppConfig.Daemon.FilePath );
        if ( fi.Exists == false ) return;

        var delay = Math.Max( 10, _viewModel.AppConfig.Daemon.IntervalSeconds );

        _ = Task.Factory.StartNew( ( ) =>
        {
            while ( cancellationToken.IsCancellationRequested is false )
            {
                var findList = Process.GetProcessesByName( fi.Name.Replace( fi.Extension, "" ) );
                if ( findList.Any( ) )
                {
                    Task.Delay( TimeSpan.FromSeconds( delay ) ).Wait( );
                    continue;
                }

                Task.Delay( TimeSpan.FromSeconds( 5 ) ).Wait( );

                ConsoleWirter.Debug( $"+ run: {fi.FullName}" );
                Core.ProcessHelper.RunProcess( fi.FullName );
            }
        }, cancellationToken );

        _logger.Info( $"注册成功" );
        await Task.CompletedTask;
    }

    public async Task StopAsync( CancellationToken cancellationToken )
    {
        _logger.Info( $"注销成功" );
        await Task.CompletedTask;
    }
}
